<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.amountStart"
        clearable
        class="filter-item"
        style="width: 105px;"
        placeholder="金额范围" />
      <span>~</span>
      <el-input v-model="listQuery.amountEnd" clearable class="filter-item" placeholder="金额范围 " style="width: 105px;" />
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="状态">
        <el-option v-for="item in couponStatusMap" :key="item.value" :label="item.name" :value="item.value" clear-all />
      </el-select>
      <el-select v-model="listQuery.issuerId" clearable style="width: 200px" class="filter-item" placeholder="发放人">
        <el-option v-for="item in adminDataMap" :key="item.id" :label="item.name" :value="item.id" clear-all />
      </el-select>
      <el-input v-model="listQuery.holder" clearable style="width: 200px" class="filter-item" placeholder="用户名" />
      <el-button
        v-permission="['operation:couponManagement:list']"
        clearable
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <el-button
        v-permission="['operation:couponManagement:batchdelete']"
        :disabled="selectedIds.length === 0"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete">批量删除</el-button>
      <el-button
        v-permission="['operation:couponManagement:grant']"
        class="filter-item"
        type="success"
        icon="el-icon-position"
        @click="handeleGrantCoupon">发放</el-button>
      <el-button
        v-permission="['operation:couponManagement:verification']"
        class="filter-item"
        type="danger"
        icon="el-icon-s-promotion"
        @click="verificationDialog">核销</el-button>
      <download-excel
        :data="exportData"
        :fields="json_fields"
        style="display: inline-block;vertical-align: middle;margin-left: 10px;"
        header="优惠券管理导出数据"
        name="优惠券管理导出数据.xls">
        <el-button class="filter-item" type="primary" icon="el-icon-download">导出</el-button>
      </download-excel>
    </div>

    <!-- 优惠券管理的表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column :selectable="checkSelectable" align="center" type="selection" width="55" />
      <el-table-column align="center" label="优惠券编码" prop="uuid" />
      <el-table-column align="center" label="单位" prop="unit" />
      <el-table-column align="center" label="金额(元)" prop="discount" />
      <el-table-column align="center" label="用户名" prop="name" />
      <el-table-column align="center" label="类型" prop="unitType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.unitType ==0 ? 'success' : 'warning'">
            {{
              scope.row.unitType == 0 ? "企业用户": "协会用户"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 0? 'info':'danger'">
            {{
              scope.row.status == 0 ? "未使用":"已核销"
            }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="使用开始时间" prop="startTime">
        <template slot-scope="scope">{{
          scope.row.startTime | formatHmt
        }}</template>
      </el-table-column>
      <el-table-column align="center" label="使用结束时间" prop="endTime">
        <template slot-scope="scope">{{
          scope.row.endTime | formatHmt
        }}</template>
      </el-table-column>
      <el-table-column align="center" label="发放人" prop="issuerName" />
      <el-table-column align="center" label="发放时间" prop="gmtCreate">
        <template slot-scope="scope">{{
          scope.row.gmtCreate | formatHmt
        }}</template>
      </el-table-column>
    </el-table>

    <!-- 发放操作的对话框 -->
    <el-dialog :visible.sync="grantVisible" title="发放优惠券">
      <div class="filter-container">
        <el-input
          v-model="listUserQuery.phone"
          clearable
          class="filter-item"
          style="width: 200px;"
          placeholder="请输入用户手机号" />
        <el-input
          v-model="listUserQuery.nickname"
          clearable
          class="filter-item"
          style="width: 200px;"
          placeholder="请输入用户名" />
        <el-button
          v-permission="['operation:couponManagement:listUserQuery']"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilterUser">查找</el-button>
        <el-button
          v-permission="['operation:couponManagement:grantCoupon']"
          :disabled="clientIds.length == 0"
          class="filter-item"
          type="success"
          icon="el-icon-position"
          @click="handleBatchCoupon">发放</el-button>
      </div>
      <!-- 发放弹窗的表格 -->
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="listUsers"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        @selection-change="handleBatchCouponChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" width="60" label="用户ID" prop="id" />
        <el-table-column align="center" label="昵称" prop="nickname" />
        <el-table-column align="center" label="手机号码" prop="phone" />
        <el-table-column align="center" label="性别" prop="gender">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.gender | genderDicFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户类型" prop="unitType">
          <template slot-scope="scope">
            <el-tag :type="scope.row.unitType == 0 ? 'success' : 'warning'">{{
              scope.row.unitType == 0 ? "企业用户" : "协会用户"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="会员等级" prop="level">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.level | levelDicFilter }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <pagination
        v-show="total1 > 0"
        :total="total1"
        :page.sync="listUserQuery.pageNo"
        :limit.sync="listUserQuery.limit"
        @pagination="getUserList" />
    </el-dialog>
    <!-- 批量发放的对话框 -->
    <el-dialog :visible.sync="grantCouponVisible" title="发放优惠券" width="700px">
      <el-form ref="grantData" :model="grantData" :rules="grantRules" label-width="150px" style="width:600px; ">
        <el-form-item label="选中的名称：">
          <el-tag v-for="item in clientNames" :key="item.value" type="info" style="margin-right:10px">
            {{ item }}
          </el-tag>
        </el-form-item>
        <el-form-item label="优惠券金额(元)：" prop="amount">
          <el-input v-model="grantData.amount" clearable style="width:205px" />
        </el-form-item>
        <el-form-item label="优惠券使用时间：">
          <el-date-picker
            v-model="grantTime"
            :picker-options="pickerOptions"
            style="width:380px"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="grantCouponVisible = false">取 消</el-button>
        <el-button type="primary" @click="createGrantData">确 定</el-button>
      </span>
    </el-dialog>
    <!--核销对话框 -->
    <el-dialog :visible.sync="verificationDialogVisible" title="核销优惠券" width="600px">
      <el-form label-width="150px" style="width:500px; ">
        <el-form-item label="优惠券编码：" prop="uuid">
          <el-input v-model="uuid" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="verificationCancelBtn">取 消</el-button>
        <el-button type="primary" @click="verificationBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 页码 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import {
  listCoupon,
  batchDeleteCoupon,
  grantCoupon,
  revocationCoupon,
  selectAdminCoupon
} from '@/api/XHCoupon'
import {
  listUser
} from '@/api/user'
const genderDic = [
  { value: 1, name: '女' },
  { value: 2, name: '男' },
  { value: '', name: '全部' }
]
const levelDic = [
  { value: 0, name: '普通会员' },
  { value: 1, name: 'VIP会员' },
  { value: '', name: '全部' }
]
export default {
  name: 'CouponManagement',
  components: { Pagination },
  filters: {
    genderDicFilter(code) {
      if (code === 1 || code === 2) {
        return genderDic[code - 1].name
      } else {
        return '未知性别'
      }
    },
    levelDicFilter(code) {
      if (code === 0 || code === 1) {
        return levelDic[code].name
      } else {
        return '未知等级'
      }
    }
  },
  data() {
    return {
      // 导出的表头
      json_fields: {
        '优惠券编码': 'uuid',
        '单位': 'unit',
        '金额（元）': 'discount',
        '用户名': 'name',
        '类型': 'unitTypeName',
        '状态': 'statusName',
        '使用开始时间': 'startTime',
        '使用结束时间': 'endTime',
        '发放人': 'issuerName',
        '发放时间': 'gmtCreate'
      },
      // 时间范围限制
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      adminDataMap: [],
      couponStatusMap: [
        { value: 0, name: '未使用' },
        { value: 1, name: '已核销' }
      ],
      selectedIds: [],
      clientIds: [],
      list: [],
      listUsers: [],
      genderDic,
      levelDic,
      grantData: {
        id: undefined,
        amount: undefined,
        startTime: undefined,
        endTime: undefined,
        clientIds: undefined
      },
      clientNames: [],
      total: 0,
      total1: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        id: undefined,
        amountStart: undefined,
        amountEnd: undefined,
        issuerId: undefined,
        holder: undefined,
        status: undefined
      },
      listUserQuery: {
        pageNo: 1,
        limit: 20,
        nickname: undefined,
        id: undefined,
        phone: undefined,
        status: undefined,
        level: undefined,
        gender: undefined,
        unitType: undefined
      },
      verificationDialogVisible: false,
      grantVisible: false,
      grantCouponVisible: false,
      grantRules: {
        amount: [
          { required: true, message: '请输入优惠券的金额', trigger: 'blur' }
        ]
      },
      uuid: undefined,
      grantTime: '',
      exportData: []
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getadminDataMap()
  },

  methods: {
    // 多选框的禁用方法
    checkSelectable(row) {
      return row.status !== 1
    },
    // 用户列表
    getUserList() {
      this.listLoading = true
      listUser(this.listUserQuery)
        .then(response => {
          this.listUsers = response.data.data.items
          this.total1 = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 发放弹窗的多选框
    handleBatchCouponChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.clientIds = temp
      const tempName = []
      e.forEach(item => {
        tempName.push(item.nickname)
      })
      this.clientNames = tempName
    },

    // 发放弹窗的发放按钮
    handleBatchCoupon(row) {
      this.grantCouponVisible = true
      // 清空数据
      this.grantData.startTime = ''
      this.grantData.endTime = ''
      this.grantData.amount = ''
      this.grantData.clientIds = []
      this.grantTime = ''
    },
    getList() {
      this.listLoading = true

      listCoupon(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          // 处理导出数据
          this.exportData = this.list
          const statusName1 = {
            statusName: '未使用'
          }
          const statusName2 = {
            statusName: '已核销'
          }
          for (var j = 0; j < this.exportData.length; j++) {
            var a = this.exportData[j].startTime.slice(0, 10)
            var b = this.exportData[j].endTime.slice(0, 10)
            var c = this.exportData[j].gmtCreate.slice(0, 10)
            this.exportData[j].startTime = a
            this.exportData[j].endTime = b
            this.exportData[j].gmtCreate = c
            if (this.exportData[j].status === 0) {
              this.exportData[j] = Object.assign(this.exportData[j], statusName1)
            } else {
              this.exportData[j] = Object.assign(this.exportData[j], statusName2)
            }
            if (this.exportData[j].unitType === 0) {
              this.exportData[j] = Object.assign(this.exportData[j], { unitTypeName: '企业用户' })
            } else {
              this.exportData[j] = Object.assign(this.exportData[j], { unitTypeName: '协会用户' })
            }
          }
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 执行批量删除
    handleBatchDelete(e) {
      this.$confirm(
        '此操作将永久删除选中的' +
        this.selectedIds.length +
        '件商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          batchDeleteCoupon(this.selectedIds)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        })
        .catch(() => {
          return false
        })
    },
    // 查询方法
    handleFilter() {
      this.listQuery.page = 1
      if (this.listQuery.amountStart) {
        if (!this.listQuery.amountEnd) {
          this.listLoading = false
          this.list = []
          return
        }
      } else if (this.listQuery.amountEnd) {
        if (!this.listQuery.amountStart) {
          this.listLoading = false
          this.list = []
          return
        }
      }
      this.getList()
    },
    // 发放优惠券的查找按钮
    handleFilterUser() {
      this.listUserQuery.page = 1

      this.getUserList()
    },
    // 优惠券管理页面的多选框
    handleSelectionChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.selectedIds = temp
      console.log(this.selectedIds, 55)
    },
    // 优惠券管理的发放按钮
    handeleGrantCoupon(row) {
      this.grantVisible = true
      this.$nextTick(function() {
        this.$refs.multipleTable.clearSelection()
      })
    },
    // 发放确定按钮
    createGrantData() {
      this.$refs['grantData'].validate(valid => {
        if (valid) {
          this.grantData.clientIds = JSON.stringify(this.clientIds)
          this.grantData.startTime = this.grantTime[0]
          this.grantData.endTime = this.grantTime[1]
          grantCoupon(this.grantData)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '发放成功！'
              })
              this.grantCouponVisible = false
              this.grantVisible = false
              // 清空表格多选框
              this.$refs.multipleTable.clearSelection()
              this.getList()
              console.log(this.grantData, 4444)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
        // }
      })
    },
    // 核销对话框
    verificationDialog() {
      this.verificationDialogVisible = true
      this.uuid = ''
    },
    // 核销确定按钮
    verificationBtn() {
      this.$confirm('此操作将核销该优惠券 ' + ' , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          revocationCoupon(this.uuid)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '核销成功'
              })
              this.verificationDialogVisible = false
              this.uuid = ''
              this.getList()
            })
            .catch(() => {
              this.$notify.success({
                title: '成功',
                message: '核销失败'
              })
            })
        })
        .catch(() => {
          return false
        })
    },
    // 核销取消按钮
    verificationCancelBtn() {
      this.verificationDialogVisible = false
      this.uuid = ''
    },
    // 发放人数据
    getadminDataMap() {
      selectAdminCoupon().then(response => {
        this.adminDataMap = response.data.data
        console.log(response)
      })
    }
  }
}
</script>
<style lang="scss">
.el-form-item__content {
  display: flex;
}
</style>
